<template>
  <a-modal
    :open="open"
    :title="$t('navigation.userMenu.changePassword')"
    @ok="handleOk"
    @cancel="handleCancel"
    :confirmLoading="loading"
    :maskClosable="false"
  >
    <a-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      layout="vertical"
    >
      <a-form-item :label="$t('navigation.userMenu.oldPassword')" name="oldPassword">
        <a-input-password
          v-model:value="formState.oldPassword"
          :placeholder="$t('navigation.userMenu.oldPasswordPlaceholder')"
        />
      </a-form-item>
      
      <a-form-item :label="$t('navigation.userMenu.newPassword')" name="newPassword">
        <a-input-password
          v-model:value="formState.newPassword"
          :placeholder="$t('navigation.userMenu.newPasswordPlaceholder')"
        />
      </a-form-item>
      
      <a-form-item :label="$t('navigation.userMenu.confirmPassword')" name="confirmPassword">
        <a-input-password
          v-model:value="formState.confirmPassword"
          :placeholder="$t('navigation.userMenu.confirmPasswordPlaceholder')"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import { authAPI } from '@/api'
import { encryptPassword } from '@/utils/crypto'

const { t } = useI18n()

defineProps<{
  open: boolean
}>()

const emit = defineEmits<{
  'update:open': [value: boolean]
}>()

const formRef = ref<FormInstance>()
const loading = ref(false)

const formState = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const validateConfirmPassword = async (_rule: any, value: string) => {
  if (value !== formState.newPassword) {
    throw new Error(t('navigation.userMenu.passwordMismatch'))
  }
}

const rules = {
  oldPassword: [
    { required: true, message: t('navigation.userMenu.oldPasswordRequired'), trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: t('navigation.userMenu.newPasswordRequired'), trigger: 'blur' },
    { min: 6, message: t('navigation.userMenu.passwordMinLength'), trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: t('navigation.userMenu.confirmPasswordRequired'), trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

const handleOk = async () => {
  try {
    await formRef.value?.validate()
    loading.value = true
    
    // 获取盐值
    const { salt } = await authAPI.getSalt()
    
    // 加密新旧密码
    const encryptedOldPassword = encryptPassword(formState.oldPassword, salt)
    const encryptedNewPassword = encryptPassword(formState.newPassword, salt)
    
    await authAPI.changePassword(encryptedOldPassword, encryptedNewPassword)
    
    message.success(t('navigation.userMenu.changePasswordSuccess'))
    handleCancel()
  } catch (error: any) {
    console.error('修改密码错误:', error)
    
    // 优先显示后端返回的友好错误消息
    let errorMessage = t('navigation.userMenu.changePasswordFailed')
    
    if (error.response?.data?.msg) {
      // 后端返回的错误消息
      errorMessage = error.response.data.msg
    } else if (error.message && !error.message.includes('status code')) {
      // 如果error.message不是技术性错误，则使用它
      errorMessage = error.message
    }
    
    message.error(errorMessage)
  } finally {
    loading.value = false
  }
}

const handleCancel = () => {
  formRef.value?.resetFields()
  emit('update:open', false)
}
</script> 